package testJdk.io.testClone;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.*;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @Description : 测试对象与序列化
 * Created by cyd on 2021-04-27 22:53:47
 */
public class ObjectStreamTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        GregorianCalendar calendar = new GregorianCalendar(2010, 2, 15);
        Date time = calendar.getTime();
        Employee emp = new Employee("jack", 5000d, time);
        Manager manager = new Manager("tom", 8000d, time);
        manager.setSecretary(emp);
        Manager manager2 = new Manager("harry", 8000d, time);
        manager2.setSecretary(emp);

        Employee[] emps = new Employee[3];
        emps[0] = emp;
        emps[1] = manager;
        emps[2] = manager2;

        // 将所有emp存入文件
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("emp.dat"));
        out.writeObject(emps);
        out.close();

        // 读取所有的emp
        ObjectInputStream oin = new ObjectInputStream(new FileInputStream("emp.dat"));
        Employee[] newEmps = (Employee[]) oin.readObject();
        oin.close();

        for (Employee e : newEmps) {
            System.out.println(e.getSalary());
        }

        System.out.println("----------------------");
        newEmps[1].raiseSalary(10);
        for (Employee e : newEmps) {
            System.out.println(e.getSalary());
        }
    }
}

@Data
@AllArgsConstructor
class Employee implements Serializable {

    private String name;
    private Double salary;
    private Date hireDate;

    public void raiseSalary(double byPercent) {
        double raised = salary * byPercent / 100;
        salary += raised;
    }
}

class Manager extends Employee {

    private Employee secretary;

    public Manager(String name, Double salary, Date hireDate) {
        super(name, salary, hireDate);
    }

    public void setSecretary(Employee secretary) {
        this.secretary = secretary;
    }

    @Override
    public String toString() {
        return "Manager{" +
                "name=" + super.getName() +
                ",salary=" + super.getSalary() +
                ",secretary=" + secretary +
                '}';
    }
}
